"use strict";
const http = require("http");
let html = `
    <!DOCTYPE html>
    <html>
        <head>
            <title>First Server</title>
        </head>
        <body>
            <div>Node.js in service</div>
        </body>
    </html>
`;
let rounterTable = {
    '/': async (req, res) => {
        res.setHeader('content-type', 'text/html;charset=utf-8');
        res.end(html);
    },
    '/x/y': async (req, res) => {
        res.end('---ok---');
    },
    '/x': async (req, res) => {
        res.end('right!!!')
    },
    '/x/y/z': async (req, res) => {
        let bufferList = [];
        let totalLength = 0;
        req.on('data', (chunk) => {
            // console.log(chunk.toString());
            totalLength += chunk.length;
            bufferList.push(chunk);
        });
        let bodyData = null;
        req.on('end', () => {
            if (bufferList.length > 0) {
                bodyData = Buffer.concat(bufferList, totalLength); //将buffer里面的内容全部都拼接起来
            }
            bufferList = []; //垃圾回收
            if (bodyData) {
                res.setHeader('content-type', 'text/plain;charset=utf-8');
                res.end(bodyData);

            } else {
                res.end();
            }
        })
    }
}
let serv = http.createServer((req, res) => {
    if (rounterTable[req.url] === undefined) {
        res.statusCode = 404;
        res.end('404 Not Found');
        return;
    }
    rounterTable[req.url](req, res) //调用上面定义的rounterTable
    // console.log(res);
    //处理Buffer数据
    // res.end(html);
});
serv.listen(3456);